package com.tentcoo.dao.impl;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.tentcoo.dao.TeacherDao;
import com.tentcoo.entity.TeacherEntity;

@Repository
public class TeacherDaoImpl implements TeacherDao {
	@Autowired
	private HibernateTemplate hibernateTemplate;

	@Autowired
	private SessionFactory sessionFactory;

	@Override
	public boolean addTeacher(TeacherEntity teacherEntity) {
		try {
			int i = (int) hibernateTemplate.save(teacherEntity);
			return true;
		} catch (DataAccessException e) {
			e.printStackTrace();
			return false;
		} catch (HibernateException e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public boolean delTeacher(String no) {
		try {
			hibernateTemplate.delete(findTeacher(no));
			return true;
		} catch (DataAccessException e) {
			e.printStackTrace();
			return false;
		} catch (HibernateException e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public boolean updateTeacher(TeacherEntity teacherEntity) {
		TeacherEntity teacher = findTeacher(teacherEntity.getNo());
		teacher.setEntity(teacherEntity);
		try {
			hibernateTemplate.update(teacher);
			return true;
		} catch (DataAccessException e) {
			e.printStackTrace();
			return false;
		} catch (HibernateException e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public TeacherEntity findTeacher(String no) {
		TeacherEntity teacher = null;
		TeacherEntity teacherEntity = new TeacherEntity();
		teacherEntity.setNo(no);
		List<TeacherEntity> list = hibernateTemplate.findByExample(teacherEntity);
		if (!list.isEmpty()) {
			teacher = list.get(0);
		}
		return teacher;
	}

}
